package com.zjsru.oneDay;

import java.util.*;

/**
 * 有效的括号
 * <p>
 * 输入：s = "(]"
 * 输出：false
 * <p>
 * 输入：s = "()[]{}"
 * 输出：true
 */
public class vaildBracket {
    public boolean isValid(String s) {
        int n = s.length();
        if (n % 2 == 1) {//当输入（）时 ，为2
            return false;
        }
        Map<Character, Character> pairs = new HashMap<Character, Character>() {
            {
                put('}', '{');
                put(']', '[');
                put(')', '(');
            }
        };
        Deque<Character> stack = new LinkedList<Character>();
        for (int i = 0; i < n; i++) {
            char ch = s.charAt(i);
            if (pairs.containsKey(ch)){ //containsKey()判断 Map 集合对象中是否包含指定的键名
                if(stack.isEmpty() || stack.peek()!= pairs.get(ch)){ //peek() 获取栈最上面那个元素
                    return false;
                }
                stack.pop();//pop()删除栈最上面的元素
            }else {
                stack.push(ch);
            }
        }
        return stack.isEmpty();
    }
    public static void main(String[] args){
        vaildBracket vaildBracket = new vaildBracket();
        System.out.println(vaildBracket.isValid("()[]{}"));
    }
}
